package pers.jing.android.helper.work

import org.slf4j.LoggerFactory
import pers.jing.android.helper.AndroidSdkTools
import pers.jing.android.helper.model.CODE_SUCCESS
import kotlin.jvm.Throws
import kotlin.time.Duration

/**
 * 自动上滑任务
 */
class AutoSwipeUpWork(
    override val duration: Duration,
    override val interval: Duration,
    /**
     * 使用设备的序列ID作为id, 每个设备每次只能有一个任务
     */
    override val id: String,
    val androidSdkPath: String,
): PeriodWork {

    private val logger = LoggerFactory.getLogger("AutoSwipeUpWork")

    @Throws
    override suspend fun run() {
        val pair = AndroidSdkTools.getWindowSize(androidSdkPath, deviceSerialId = id)
        if (pair == null) {
            throw Exception("getWindowSize Failure")
        }
        val (width, height) = pair
        val middleWidth = width / 2
        val middleHeight = height / 2
        //自测这里的滑动距离从中间-100到100是不行, 无法正确识别上滑手势
        val startPoint = Pair(middleWidth, (middleHeight + 300).coerceAtMost(height))
        val endPoint = Pair(middleWidth, (middleHeight - 300).coerceAtLeast(0))
        val cResult = AndroidSdkTools.swipe(androidSdkPath, deviceSerialId = id,
            startPoint = startPoint,
            endPoint = endPoint,
            duration = 300)
        if (CODE_SUCCESS == cResult.code) {
            //执行成功
            logger.info("swipe up success")
        } else {
            //执行失败, 跳出循环
            throw Exception(cResult.error?.joinToString("\n")?:"unknown")
        }
    }
}